<template>
<div id="classify">
  <el-tree :data="classifyData" node-key="lid" default-expand-all :expand-on-click-node="false">
    <span class="custom-tree-node" slot-scope="{ node, data }" style="width:100%">
      <span style="float:left">{{ data.label }}</span>
      <span style="float:right" v-if="data.level == 0">
        <el-button type="text" size="mini" @click="() => openClassifyModal(data)">
          增加
        </el-button>
      </span>
    </span>
  </el-tree>
  <el-dialog title="新增分类" :visible.sync="dialogFormVisible" width="30%">
    <el-form ref="form" :rules="rules" :model="classify">
      <el-form-item label="分类名称" prop="label">
        <el-input v-model="classify.label" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="appendClassify()">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import http from '@/components/service/http.js'

export default {
  name: 'classify',
  data() {
    return {
      dialogFormVisible: false,
      classify: {
        parent: {},
        label: '',
      },
      classifyData: [],
      rules: {
        label: [{
          required: true,
          message: '请输入分类名称',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getClassifyData();
  },
  methods: {
    getClassifyData: function () {
      var This = this;
      http.get('/shs/classify/getList').then(function (rep) {
        This.classifyData = rep.data;
      })
    },
    openClassifyModal: function (data) {
      this.classify.parent = data;
      this.dialogFormVisible = true;
    },
    appendClassify: function () {
      var This = this;

      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!This.classify.parent.children) {
            This.classify.parent.children = []
          }

          This.classify.parent.children.push({
            label: This.classify.label
          })
          http.post('/shs/classify/save', This.classify.parent).then(function (rep) {
            This.classify = {
              parent: {},
              label: '',
            }
            This.getClassifyData();
            This.dialogFormVisible = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>
#classify {
  width: 100%;
}
</style>
